define(['app', 'blockUI', 'jquery'], function (app) {
    app.controller('evalTempl', function ($scope, $rootScope, $http, blockUI, $timeout, $modal, $log) {


        // blockUI.start("数据读取中~")
        // $timeout(function() {
        //     $scope.$apply(function() {
        //         blockUI.stop();
        //     });
        // }, 2000, false)
        //初始化表格,获取当前所有模板
        //获取页面数据


        $http({
            url: '/OSRS/evaltempl/templtelist?pageNow=1',
            method: 'get'
        }).then(function (res) {
            // layer.msg("进来了dklfjldjgldkjgdfklj");
            $scope.data = res.data.pageDatas;
            console.log($scope.data)
            $scope.totalRecord = res.data.totalRecords;
            $scope.pageNow = res.data.pageNow;
            $scope.pageSize = res.data.pageSize;
            layui.use(['table', 'laypage'], function () {
                var table = layui.table;
                var laypage = layui.laypage;
                //执行一个laypage实例
                laypage.render({
                    elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
                    count: $scope.totalRecord,//页总数，从服务端得到
                    curr: $scope.pageNow,
                    limit: $scope.pageSize,
                    jump: function (obj, first) {
                        //首次不执行
                        if (!first) {
                            //obj包含了当前分页的所有参数，比如：


                            $http({
                                method: 'GET',
                                url: '/OSRS/evaltempl/templtelist?pageNow=' + obj.curr
                            }).then(function (res) {
                                $scope.data = res.data.pageDatas;
                                $scope.totalRecord = res.data.totalRecords;
                                $scope.pageNow = res.data.pageNow;
                                $scope.pageSize = res.data.pageSize;
                            });

                        }
                    }
                });
            });
        }, function (err) {
            layer.msg("数据加载异常")
        })
        $scope.all = false;
        $scope.titleShow = true;
        $scope.allChk = function () {
            $scope.titleShow = !$scope.all;

            $scope.data.map(function (value) {
                value.chk = $scope.all;
                console.log(value.chk);
                return value
            })
        }
        $scope.itemChk = function (val) {
            console.log(val);
            console.log($scope.data);
            var anyonetrue = false,
                anyonefalse = false
            for (var i = 0; i < $scope.data.length; i++) {
                if ($scope.data [i].chk == false) {
                    $scope.all = false;
                    anyonefalse = true
                } else {
                    anyonetrue = true
                }
            }
            $scope.all = !anyonefalse;
            $scope.titleShow = !anyonetrue;
            if (!val) {
                $scope.all = false;
            } else {
                $scope.titleShow = false;
            }

        }

        $scope.addtempl = function () {

            //$rootScope.data.data.unshift(data)
            //$scope.open($rootScope.data.data[0], 0)
            // if ($rootScope.copydata != undefined) {
            //     $rootScope.data = $rootScope.copydata;
            // } else {
            $rootScope.data = {
                "tempid": 0,
                "status": 1,
                "remark": "备注",
                "tempname": "标题",
                "researchadvices": [{
                    "adviceid": 1,
                    "title": "建议1",
                    "researchTemplate": null
                }],
                "questioncategories": [{
                    "cateid": 1,
                    "title": "调查标题1",
                    "researchquestions": [{
                        "questionid": 1,
                        "title": "问题1",
                        "questionCategory": null
                    }]
                }],
                "researchTemplate": null
            };
            // }

            $scope.open($rootScope.data, 0)
        }
        $('body').scrollTop(0);
        $rootScope.initData = function () {
            $http({
                url: '/OSRS/evaltempl/templtelist?pageNow=1&time=' + Math.random(),
                method: 'post'
            }).then(function (res) {
                console.log($scope.data);
                $scope.data = res.data.pageDatas;
                $scope.totalRecord = res.data.totalRecords;
                $scope.pageNow = res.data.pageNow;
                $scope.pageSize = res.data.pageSize;
                layui.use(['table', 'laypage'], function () {
                    var table = layui.table;
                    var laypage = layui.laypage;
                    //执行一个laypage实例
                    laypage.render({
                        elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
                        count: $scope.totalRecord,//页总数，从服务端得到
                        curr: $scope.pageNow,
                        limit: $scope.pageSize,
                        jump: function (obj, first) {
                            //首次不执行
                            if (!first) {
                                //obj包含了当前分页的所有参数，比如：


                                $http({
                                    method: 'GET',
                                    url: '/OSRS/evaltempl/templtelist?pageNow=' + obj.curr
                                }).then(function (res) {
                                    $scope.data = res.data.pageDatas;
                                    $scope.totalRecord = res.data.totalRecords;
                                    $scope.pageNow = res.data.pageNow;
                                    $scope.pageSize = res.data.pageSize;
                                });

                            }
                        }
                    });
                });

            }, function (err) {
                layer.msg("数据加载异常")
            })


        }

        //启用,禁用
        $scope.change = function () {

            var ids = '';
            for (var i = 0; i < $scope.data.length; i++) {
                if ($scope.data [i].chk == true) {
                    ids += $scope.data [i].tempid;
                    ids += ','
                }
            }

            if (ids.length > 0) {
                $http({
                    url: '/OSRS/evaltempl/change',
                    method: 'post',
                    data: ids
                }).then(function (res) {
                    if (res.data == "ok") {
                        layer.msg("操作成功");
                    } else if (res.data == "x") {
                        layer.msg("部分模板在使用中无法切换状态");
                    }

                    $rootScope.initData();
                })
            }
        }
        //删除
        $scope.delete = function () {
            var ids = '';
            for (var i = 0; i < $scope.data.length; i++) {
                if ($scope.data [i].chk == true) {

                    alert($scope.data [i].tempid);
                    ids += $scope.data [i].tempid;
                    ids += ','
                }
            }

            if (ids.length > 0) {
                $http({
                    url: '/OSRS/evaltempl/delete',
                    method: 'post',
                    data: ids
                }).then(function (res) {
                    layer.msg("删除成功");
                    $rootScope.initData();
                })
            }
        }
        //ng模态框部分
        //		$rootScope.ddd = "12345qwer"
        // list
        // open click
        $scope.open = function (x, disable) {
            var modalInstance = $modal.open({
                templateUrl: 'evalTempl.html',
                controller: 'evalTemplModalCtrl', // specify controller for modal
                //size: size,
                resolve: {
                    items: function () {
                        return x;
                    }
                }
            });
            // modal return result
            modalInstance.result.then(function (selectedItem) {
                $scope.selected = selectedItem;
            }, function () {
                // $log.info('Modal dismissed at: ' + new Date())
            });
        };
        //模板操作-预览
        $scope.preview = function (x) {
            /* if (!x.hascon) {
             return layer.confirm("该模板尚未添加考评内容，请先编辑", {
             icon: 0,
             title: "提示",
             btn: ['好']
             }, function (index) {
             layer.close(index)
             })
             }*/
            //弹出编辑模态窗口
            console.log(JSON.stringify(x));
            window.open("/OSRS/evaltempl/pre?id=" + x.tempid);
            //$scope.open(x,1)
        };
        // //设置cookie 封装函数
        // function setCookie(k, v, ex) {
        //     var now = new Date()
        //     var d = now.getDate()
        //     now.setDate(d + ex)
        //     document.cookie = k + "=" + v + ";expires=" + now.toUTCString();
        // }
        //模板操作-编辑
        $scope.edit = function (x) {
            if (x.status == 2) {
                return layer.confirm("该模板正在使用中，无法编辑", {
                    icon: 0,
                    title: "提示",
                    btn: ['好']
                }, function (index) {
                    layer.close(index)
                })
            }
            //弹出编辑模态窗口
            $http({
                method: 'POST',
                url: '/OSRS/temple/mod',
                data: x.tempid
            }).then(function (res) {
                console.log(res.data);
                $scope.open(res.data, 0);
                $rootScope.data = res.data;

            }, function (err) {
                layer.msg("服务器未响应");
            });

        }
        //模板操作-复制
        $scope.templcopy = function (x) {
            console.log(x);
            $http({
                method: 'POST',
                url: '/OSRS/temple/mod',
                data: x.tempid
            }).then(function (res) {
                console.log(res.data);
                $rootScope.copydata = res.data;
                $rootScope.copydata.tempid = 0;
                $rootScope.data = $rootScope.copydata;
                $scope.open($rootScope.data, 0)
            }, function (err) {
                layer.msg("复制失败");
            });

        }
        //模板操作-删除
        $scope.del = function (x) {
            $http({
                method: "post",
                url: "",
                data: x.id
            }).then(function (res) {
                layer.msg("模板删除成功");

            }, function (err) {
                layer.msg("模板删除失败");

            })
        }
    });
    app.controller('evalTemplModalCtrl', function ($rootScope, $scope, $modalInstance, items, $http) {
        $scope.items = items;

        $scope.leimuAdd = function () {
            var length = items.questioncategories.length + 1;
            var obj = {
                cateid: length,
                title: "",
                researchTemplate: null,
                researchquestions: [{questionid: 1, title: "问题1", questionCategory: null}]
            };
            $rootScope.data.questioncategories.push(obj);


        }
        $scope.leimuRm = function (index) {
            $rootScope.data.questioncategories.splice(index, 1);
        }
        $scope.leimuItemAdd = function (upindex) {
            var length = items.questioncategories[upindex].researchquestions.length + 1;
            var obj = {questionid: length, title: "", questionCategory: null};
            $rootScope.data.questioncategories[upindex].researchquestions.push(obj)
        }
        $scope.leimuItemRm = function (upindex, index) {

            $rootScope.data.questioncategories[upindex].researchquestions.splice(index, 1)

        }

        $scope.suggestionAdd = function () {
            var length = items.researchadvices.length + 1;
            var obj = {adviceid: length, title: "", researchTemplate: null};
            $rootScope.data.researchadvices.push(obj)
        };
        $scope.suggestionRm = function (index) {
            $rootScope.data.researchadvices.splice(index, 1);
        };
        // ok click
        $scope.ok = function () {

            var myInput = document.getElementById("modtemp").getElementsByTagName("input");
            var isfill = true;
            for (var i = 0; i < myInput.length; i++) {
                if (myInput[i].value.trim().length == 0) {
                    isfill = false;
                    break
                }
            }

            if (isfill) {
                layer.confirm("确定修改？", {
                    icon: 0,
                    title: "提示",
                    btn: ["确认", "取消"]
                }, function (index) {
                    layer.close(index);
                    // 发送至后端
                    $http({
                        method: "post",
                        url: "/OSRS/temple/domod",
                        data: $rootScope.data
                    }).then(function (res) {
                        if (res.data == "ok") {
                            layer.msg("修改成功");
                            $rootScope.initData();
                        } else {
                            layer.msg("修改失败");
                        }
                    }, function (err) {
                        layer.msg("服务器未响应");
                    })
                    $modalInstance.close('ok');
                }, function (index) {
                    layer.close(index);

                })
            } else {
                layer.msg("请填入数据");
            }
        };

        // cancel click
        $scope.cancel = function () {
            layer.confirm("确定退出？", {
                icon: 0,
                title: "提示",
                btn: ["确定", "取消"]
            }, function (index) {
                layer.close(index);
                $modalInstance.dismiss('cancel');
            }, function (index) {
                layer.close(index);
            })

        }
    });
});